# AI智能化功能视图
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required, permission_required
from django.http import JsonResponse, HttpResponse
from django.views.decorators.http import require_http_methods
from django.contrib import messages
from django.core.paginator import Paginator
from django.db.models import Q, Count, Sum, Avg
from django.utils import timezone
from datetime import datetime, timedelta
import json
import logging

from .models import Asset, AssetCategory, Department, MaintenanceRecord
from .models_ai import AssetRecommendation, AssetAnomalyDetection, PredictiveMaintenanceModel, AssetUtilizationAnalysis
from .ai_engine import ai_recommendation_engine, anomaly_detection_service, predictive_maintenance_service

logger = logging.getLogger(__name__)


@login_required
def ai_dashboard(request):
    """AI智能化功能仪表板"""
    # 获取用户的推荐数据
    recommendations = AssetRecommendation.objects.filter(
        user=request.user,
        is_dismissed=False
    ).order_by('-created_at')[:10]
    
    # 获取异常检测数据
    anomalies = AssetAnomalyDetection.objects.filter(
        is_resolved=False
    ).order_by('-detected_at')[:10]
    
    # 统计数据
    stats = {
        'total_recommendations': AssetRecommendation.objects.filter(user=request.user).count(),
        'unread_recommendations': AssetRecommendation.objects.filter(user=request.user, is_read=False).count(),
        'active_anomalies': AssetAnomalyDetection.objects.filter(is_resolved=False).count(),
        'resolved_anomalies': AssetAnomalyDetection.objects.filter(is_resolved=True).count(),
    }
    
    # 推荐类型分布
    recommendation_types = AssetRecommendation.objects.filter(
        user=request.user
    ).values('recommendation_type').annotate(
        count=Count('id')
    ).order_by('-count')
    
    context = {
        'recommendations': recommendations,
        'anomalies': anomalies,
        'stats': stats,
        'recommendation_types': recommendation_types,
    }
    
    return render(request, 'assets/ai/dashboard.html', context)


@login_required
def recommendations_list(request):
    """推荐列表页面"""
    # 获取筛选参数
    recommendation_type = request.GET.get('type', '')
    priority = request.GET.get('priority', '')
    status = request.GET.get('status', 'all')
    
    # 构建查询
    recommendations = AssetRecommendation.objects.filter(user=request.user)
    
    if recommendation_type:
        recommendations = recommendations.filter(recommendation_type=recommendation_type)
    
    if priority:
        recommendations = recommendations.filter(priority=priority)
    
    if status == 'unread':
        recommendations = recommendations.filter(is_read=False)
    elif status == 'accepted':
        recommendations = recommendations.filter(is_accepted=True)
    elif status == 'dismissed':
        recommendations = recommendations.filter(is_dismissed=True)
    
    recommendations = recommendations.order_by('-created_at')
    
    # 分页
    paginator = Paginator(recommendations, 20)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'recommendation_types': AssetRecommendation.RECOMMENDATION_TYPE_CHOICES,
        'priorities': AssetRecommendation.PRIORITY_CHOICES,
        'current_filters': {
            'type': recommendation_type,
            'priority': priority,
            'status': status,
        }
    }
    
    return render(request, 'assets/ai/recommendations_list.html', context)


@login_required
@require_http_methods(["POST"])
def generate_recommendations(request):
    """生成推荐"""
    try:
        data = json.loads(request.body)
        recommendation_type = data.get('type', 'all')
        asset_id = data.get('asset_id')
        department_id = data.get('department_id')
        category_id = data.get('category_id')
        
        recommendations = []
        
        if recommendation_type in ['all', 'maintenance']:
            # 生成维修推荐
            asset = None
            if asset_id:
                asset = get_object_or_404(Asset, id=asset_id)
            
            maintenance_recs = ai_recommendation_engine.generate_maintenance_recommendations(
                user=request.user,
                asset=asset
            )
            recommendations.extend(maintenance_recs)
        
        if recommendation_type in ['all', 'replacement']:
            # 生成更换推荐
            department = None
            if department_id:
                department = get_object_or_404(Department, id=department_id)
            
            replacement_recs = ai_recommendation_engine.generate_replacement_recommendations(
                user=request.user,
                department=department
            )
            recommendations.extend(replacement_recs)
        
        if recommendation_type in ['all', 'optimization']:
            # 生成优化推荐
            category = None
            if category_id:
                category = get_object_or_404(AssetCategory, id=category_id)
            
            optimization_recs = ai_recommendation_engine.generate_optimization_recommendations(
                user=request.user,
                category=category
            )
            recommendations.extend(optimization_recs)
        
        return JsonResponse({
            'success': True,
            'message': f'成功生成 {len(recommendations)} 条推荐',
            'count': len(recommendations)
        })
        
    except Exception as e:
        logger.error(f"生成推荐时出错: {e}")
        return JsonResponse({
            'success': False,
            'message': f'生成推荐失败: {str(e)}'
        }, status=500)


@login_required
@require_http_methods(["POST"])
def handle_recommendation(request, recommendation_id):
    """处理推荐（接受/忽略）"""
    try:
        recommendation = get_object_or_404(AssetRecommendation, id=recommendation_id, user=request.user)
        data = json.loads(request.body)
        action = data.get('action')
        
        if action == 'accept':
            recommendation.accept()
            message = '推荐已接受'
        elif action == 'dismiss':
            recommendation.dismiss()
            message = '推荐已忽略'
        elif action == 'mark_read':
            recommendation.mark_as_read()
            message = '推荐已标记为已读'
        else:
            return JsonResponse({'success': False, 'message': '无效的操作'}, status=400)
        
        return JsonResponse({
            'success': True,
            'message': message
        })
        
    except Exception as e:
        logger.error(f"处理推荐时出错: {e}")
        return JsonResponse({
            'success': False,
            'message': f'处理推荐失败: {str(e)}'
        }, status=500)


@login_required
def anomaly_detection_list(request):
    """异常检测列表"""
    # 获取筛选参数
    anomaly_type = request.GET.get('type', '')
    severity = request.GET.get('severity', '')
    status = request.GET.get('status', 'all')
    
    # 构建查询
    anomalies = AssetAnomalyDetection.objects.select_related('asset')
    
    if anomaly_type:
        anomalies = anomalies.filter(anomaly_type=anomaly_type)
    
    if severity:
        anomalies = anomalies.filter(severity=severity)
    
    if status == 'unconfirmed':
        anomalies = anomalies.filter(is_confirmed=False)
    elif status == 'confirmed':
        anomalies = anomalies.filter(is_confirmed=True, is_resolved=False)
    elif status == 'resolved':
        anomalies = anomalies.filter(is_resolved=True)
    
    anomalies = anomalies.order_by('-detected_at')
    
    # 分页
    paginator = Paginator(anomalies, 20)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'anomaly_types': AssetAnomalyDetection.ANOMALY_TYPE_CHOICES,
        'severities': AssetAnomalyDetection.SEVERITY_CHOICES,
        'current_filters': {
            'type': anomaly_type,
            'severity': severity,
            'status': status,
        }
    }
    
    return render(request, 'assets/ai/anomaly_detection_list.html', context)


@login_required
@require_http_methods(["POST"])
def run_anomaly_detection(request):
    """运行异常检测"""
    try:
        data = json.loads(request.body)
        detection_type = data.get('type', 'all')
        asset_id = data.get('asset_id')
        
        detected_anomalies = []
        
        if asset_id:
            # 对指定资产进行检测
            asset = get_object_or_404(Asset, id=asset_id)
            assets = [asset]
        else:
            # 对所有资产进行检测
            assets = Asset.objects.filter(status='in_use')
        
        for asset in assets:
            if detection_type in ['all', 'usage']:
                # 使用模式异常检测
                usage_anomaly = anomaly_detection_service.detect_usage_anomalies(asset)
                if usage_anomaly:
                    detected_anomalies.append(usage_anomaly)
            
            if detection_type in ['all', 'frequency']:
                # 维修频率异常检测
                frequency_anomaly = anomaly_detection_service.detect_frequency_anomalies(asset)
                if frequency_anomaly:
                    detected_anomalies.append(frequency_anomaly)
        
        if detection_type in ['all', 'cost']:
            # 成本异常检测
            recent_maintenance = MaintenanceRecord.objects.filter(
                created_at__gte=timezone.now() - timedelta(days=90)
            )
            cost_anomalies = anomaly_detection_service.detect_cost_anomalies(list(recent_maintenance))
            detected_anomalies.extend(cost_anomalies)
        
        return JsonResponse({
            'success': True,
            'message': f'检测完成，发现 {len(detected_anomalies)} 个异常',
            'count': len(detected_anomalies)
        })
        
    except Exception as e:
        logger.error(f"运行异常检测时出错: {e}")
        return JsonResponse({
            'success': False,
            'message': f'异常检测失败: {str(e)}'
        }, status=500)


@login_required
@require_http_methods(["POST"])
def handle_anomaly(request, anomaly_id):
    """处理异常（确认/解决）"""
    try:
        anomaly = get_object_or_404(AssetAnomalyDetection, id=anomaly_id)
        data = json.loads(request.body)
        action = data.get('action')
        notes = data.get('notes', '')
        
        if action == 'confirm':
            anomaly.confirm(request.user, notes)
            message = '异常已确认'
        elif action == 'resolve':
            anomaly.resolve(request.user, notes)
            message = '异常已解决'
        else:
            return JsonResponse({'success': False, 'message': '无效的操作'}, status=400)
        
        return JsonResponse({
            'success': True,
            'message': message
        })
        
    except Exception as e:
        logger.error(f"处理异常时出错: {e}")
        return JsonResponse({
            'success': False,
            'message': f'处理异常失败: {str(e)}'
        }, status=500)


@login_required
def predictive_maintenance(request):
    """预测性维护页面"""
    # 获取筛选参数
    category_id = request.GET.get('category')
    department_id = request.GET.get('department')
    days_ahead = int(request.GET.get('days_ahead', 30))
    
    # 构建查询
    assets = Asset.objects.filter(status='in_use').select_related('category', 'department')
    
    if category_id:
        assets = assets.filter(category_id=category_id)
    
    if department_id:
        assets = assets.filter(department_id=department_id)
    
    # 生成预测数据
    predictions = []
    for asset in assets:
        prediction = predictive_maintenance_service.predict_maintenance_needs(asset, days_ahead)
        predictions.append({
            'asset': asset,
            'prediction': prediction
        })
    
    # 按预测日期排序
    predictions.sort(key=lambda x: x['prediction']['days_until'])
    
    # 分页
    paginator = Paginator(predictions, 20)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'categories': AssetCategory.objects.all(),
        'departments': Department.objects.all(),
        'current_filters': {
            'category': category_id,
            'department': department_id,
            'days_ahead': days_ahead,
        }
    }
    
    return render(request, 'assets/ai/predictive_maintenance.html', context)


@login_required
def asset_prediction_detail(request, asset_id):
    """资产预测详情"""
    asset = get_object_or_404(Asset, id=asset_id)
    
    # 获取预测数据
    prediction = predictive_maintenance_service.predict_maintenance_needs(asset)
    
    # 获取历史维修记录
    maintenance_history = MaintenanceRecord.objects.filter(
        asset=asset
    ).order_by('-created_at')[:10]
    
    # 获取相关推荐
    recommendations = AssetRecommendation.objects.filter(
        asset=asset,
        is_dismissed=False
    ).order_by('-created_at')[:5]
    
    # 获取异常记录
    anomalies = AssetAnomalyDetection.objects.filter(
        asset=asset
    ).order_by('-detected_at')[:5]
    
    context = {
        'asset': asset,
        'prediction': prediction,
        'maintenance_history': maintenance_history,
        'recommendations': recommendations,
        'anomalies': anomalies,
    }
    
    return render(request, 'assets/ai/asset_prediction_detail.html', context)


@login_required
def ai_analytics(request):
    """AI分析统计页面"""
    # 推荐统计
    recommendation_stats = {
        'total': AssetRecommendation.objects.count(),
        'by_type': AssetRecommendation.objects.values('recommendation_type').annotate(
            count=Count('id')
        ).order_by('-count'),
        'by_priority': AssetRecommendation.objects.values('priority').annotate(
            count=Count('id')
        ).order_by('-count'),
        'acceptance_rate': 0
    }
    
    # 计算接受率
    total_recs = AssetRecommendation.objects.count()
    accepted_recs = AssetRecommendation.objects.filter(is_accepted=True).count()
    if total_recs > 0:
        recommendation_stats['acceptance_rate'] = (accepted_recs / total_recs) * 100
    
    # 异常检测统计
    anomaly_stats = {
        'total': AssetAnomalyDetection.objects.count(),
        'by_type': AssetAnomalyDetection.objects.values('anomaly_type').annotate(
            count=Count('id')
        ).order_by('-count'),
        'by_severity': AssetAnomalyDetection.objects.values('severity').annotate(
            count=Count('id')
        ).order_by('-count'),
        'resolution_rate': 0
    }
    
    # 计算解决率
    total_anomalies = AssetAnomalyDetection.objects.count()
    resolved_anomalies = AssetAnomalyDetection.objects.filter(is_resolved=True).count()
    if total_anomalies > 0:
        anomaly_stats['resolution_rate'] = (resolved_anomalies / total_anomalies) * 100
    
    # 预测模型统计
    model_stats = {
        'total_models': PredictiveMaintenanceModel.objects.count(),
        'active_models': PredictiveMaintenanceModel.objects.filter(is_active=True).count(),
        'avg_accuracy': PredictiveMaintenanceModel.objects.filter(
            is_active=True
        ).aggregate(avg_accuracy=Avg('accuracy'))['avg_accuracy'] or 0
    }
    
    context = {
        'recommendation_stats': recommendation_stats,
        'anomaly_stats': anomaly_stats,
        'model_stats': model_stats,
    }
    
    return render(request, 'assets/ai/analytics.html', context)


# API接口
@login_required
@require_http_methods(["GET"])
def api_recommendations(request):
    """推荐API接口"""
    try:
        recommendations = AssetRecommendation.objects.filter(
            user=request.user,
            is_dismissed=False
        ).select_related('asset', 'category', 'department').order_by('-created_at')[:20]
        
        data = []
        for rec in recommendations:
            data.append({
                'id': rec.id,
                'type': rec.recommendation_type,
                'title': rec.title,
                'description': rec.description,
                'priority': rec.priority,
                'confidence_score': rec.confidence_score,
                'is_read': rec.is_read,
                'created_at': rec.created_at.isoformat(),
                'asset': {
                    'id': rec.asset.id,
                    'name': rec.asset.name,
                    'asset_number': rec.asset.asset_number
                } if rec.asset else None
            })
        
        return JsonResponse({
            'success': True,
            'data': data,
            'count': len(data)
        })
        
    except Exception as e:
        logger.error(f"获取推荐API数据时出错: {e}")
        return JsonResponse({
            'success': False,
            'message': str(e)
        }, status=500)


@login_required
@require_http_methods(["GET"])
def api_anomalies(request):
    """异常检测API接口"""
    try:
        anomalies = AssetAnomalyDetection.objects.filter(
            is_resolved=False
        ).select_related('asset').order_by('-detected_at')[:20]
        
        data = []
        for anomaly in anomalies:
            data.append({
                'id': anomaly.id,
                'type': anomaly.anomaly_type,
                'severity': anomaly.severity,
                'description': anomaly.description,
                'confidence_score': anomaly.confidence_score,
                'is_confirmed': anomaly.is_confirmed,
                'detected_at': anomaly.detected_at.isoformat(),
                'asset': {
                    'id': anomaly.asset.id,
                    'name': anomaly.asset.name,
                    'asset_number': anomaly.asset.asset_number
                }
            })
        
        return JsonResponse({
            'success': True,
            'data': data,
            'count': len(data)
        })
        
    except Exception as e:
        logger.error(f"获取异常检测API数据时出错: {e}")
        return JsonResponse({
            'success': False,
            'message': str(e)
        }, status=500)